<template>
  <div class="container">
    <a-card class="general-card">
      <!-- 搜索区域 -->
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="组织名称">
                  <a-input v-model="searchForm.groupName" placeholder="请输入组织名称" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <!-- 工具栏 -->
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon><icon-plus /></template>
              新建
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data="pageData"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        row-key="groupId"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #action="{ record }">
          <a-space>
            <a-button v-if="record.groupId !== 1" type="text" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-button v-if="record.groupId !== 1" type="text" size="small" status="danger" @click="handleDelete(record)"
              >删除</a-button
            >
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 弹窗：群组表单 -->
    <a-modal v-model:visible="formVisible" :title="formTitle" :width="380" @ok="handleSubmit" @cancel="handleCancel">
      <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical" class="group-modal-form">
        <a-form-item field="groupName" label="群组名称" required>
          <a-input v-model="formData.groupName" placeholder="请输入群组名称" />
        </a-form-item>
        <a-form-item field="groupDsc" label="群组描述">
          <a-textarea v-model="formData.groupDsc" placeholder="请输入群组描述" :rows="3" />
        </a-form-item>
        <a-form-item field="upGroupId" label="上级群组">
          <a-select v-model="formData.upGroupId" placeholder="请选择上级群组" allow-clear>
            <a-option v-for="item in allGroups" :key="item.groupId" :value="item.groupId">
              {{ item.groupName }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import { queryGroupList, addGroup, updateGroup, deleteGroup, GroupInfo, queryGroupListAll } from '@/api/group';

  const loading = ref(false);
  const tableData = ref<GroupInfo[]>([]); // 全部数据
  const pageData = ref<GroupInfo[]>([]); // 当前页数据
  const allGroupsData = ref<GroupInfo[]>([]); // 所有群组数据（用于下拉选项）
  const selectedRowKeys = ref<number[]>([]);
  const formVisible = ref(false);
  const formTitle = ref('新增群组');
  const formRef = ref();

  const formData = reactive<GroupInfo>({
    groupId: undefined,
    groupName: '',
    groupDsc: '',
    upGroupId: undefined
  });

  const formRules = {
    groupName: [{ required: true, message: '请输入群组名称' }]
  };

  const searchForm = reactive({
    groupName: ''
  });

  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 50]
  });

  const rowSelection = {
    type: 'checkbox',
    get selectedRowKeys() {
      return Array.isArray(selectedRowKeys.value) ? selectedRowKeys.value : [];
    },
    onChange: (keys: number[]) => {
      selectedRowKeys.value = Array.isArray(keys) ? keys : [];
    }
  };

  const allGroups = computed(() => allGroupsData.value);

  const columns = [
    { title: '群组ID', dataIndex: 'groupId' },
    { title: '群组名称', dataIndex: 'groupName' },
    { title: '群组描述', dataIndex: 'groupDsc' },
    {
      title: '上级群组',
      dataIndex: 'upGroupId',
      render: ({ record }) => {
        const up = allGroupsData.value.find(g => g.groupId === record.upGroupId);
        return up ? up.groupName : '-';
      }
    },
    {
      title: '操作',
      slotName: 'action',
      fixed: 'right'
    }
  ];

  const fetchGroupList = async () => {
    loading.value = true;
    try {
      const params = {
        groupName: searchForm.groupName,
        pageNo: pagination.current,
        pageSize: pagination.pageSize
      };
      const response: any = await queryGroupList(params);
      if (response.code === 200 || response.code === 0) {
        tableData.value = response.data?.rows || [];
        pagination.total = response.data?.page?.totalRow || tableData.value.length;
        pageData.value = tableData.value;
      } else {
        Message.error(response.message || '获取群组列表失败');
      }
    } catch (error) {
      console.error('获取群组列表错误:', error);
      Message.error('获取群组列表失败');
    } finally {
      loading.value = false;
    }
  };

  const handleSearch = () => {
    pagination.current = 1;
    fetchGroupList();
  };

  const handleReset = () => {
    searchForm.groupName = '';
    pagination.current = 1;
    fetchGroupList();
  };

  const onPageChange = (page: number) => {
    pagination.current = page;
    fetchGroupList();
  };

  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchGroupList();
  };

  const handleAdd = () => {
    formTitle.value = '新增群组';
    Object.assign(formData, {
      groupId: undefined,
      groupName: '',
      groupDsc: '',
      upGroupId: undefined
    });
    formVisible.value = true;
  };

  const handleEdit = (record: GroupInfo) => {
    formTitle.value = '编辑群组';
    Object.assign(formData, record);
    formVisible.value = true;
  };

  const handleDelete = (record: GroupInfo) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除群组 "${record.groupName}" 吗？`,
      onOk: async () => {
        try {
          await deleteGroup(record.groupId!);
          Message.success('删除成功');
          fetchGroupList();
        } catch (error) {
          Message.error('删除失败');
        }
      }
    });
  };

  const handleSubmit = async () => {
    try {
      await formRef.value.validate();
      if (formTitle.value === '新增群组') {
        await addGroup({
          groupName: formData.groupName,
          groupDsc: formData.groupDsc,
          upGroupId: formData.upGroupId || null
        });
        Message.success('新增成功');
      } else {
        await updateGroup({
          groupId: formData.groupId,
          groupName: formData.groupName,
          groupDsc: formData.groupDsc,
          upGroupId: formData.upGroupId || null
        });
        Message.success('更新成功');
      }
      formVisible.value = false;
      fetchGroupList();
    } catch (error) {
      console.error('提交表单错误:', error);
      Message.error('操作失败');
    }
  };

  const handleCancel = () => {
    formVisible.value = false;
  };

  // 获取所有群组列表（用于下拉选项）
  const fetchAllGroups = async () => {
    try {
      const response: any = await queryGroupListAll();
      if (response.code === 200 || response.code === 0) {
        allGroupsData.value = response.data || [];
      }
    } catch (error) {
      console.error('获取所有群组列表错误:', error);
    }
  };

  fetchGroupList();
  fetchAllGroups();
</script>

<style lang="less" scoped>
  .container {
    padding: 20px;
  }
  .group-modal-form :deep(.arco-form-item-content) {
    width: 350px !important;
    min-width: 0 !important;
    max-width: 350px !important;
  }
  .group-modal-form :deep(.arco-input-wrapper),
  .group-modal-form :deep(.arco-input),
  .group-modal-form :deep(.arco-textarea) {
    width: 350px !important;
    min-width: 0 !important;
    max-width: 350px !important;
    box-sizing: border-box;
  }
</style>
